package com.fullstack.landscape.editor.controller;

import com.fullstack.landscape.editor.common.Result;
import com.fullstack.landscape.editor.controller.vo.ModuleVO;
import com.fullstack.landscape.editor.service.ModuleService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Objects;

/**
 * @author leven.chen
 * @project landscape-editor
 * @date 2019/4/9 19:02
 * @apiNote
 */
@RestController
@RequestMapping("/api/module")
public class ModuleController {

    @Autowired
    private ModuleService moduleService;

    @GetMapping("/list")
    public Result<List<ModuleVO>> getList() {
        List<ModuleVO> list = moduleService.getList();
        return Result.success(list);
    }


    @PostMapping("/update/{id}")
    public Result<Void> update(@PathVariable int id,
                               @RequestParam(value = "name", required = false) String name,
                               @RequestParam(value = "avatarPath", required = false) String avatarPath) {
        moduleService.update(id, name, avatarPath);
        return Result.success();
    }

    @PostMapping("/delete/{id}")
    public Result<Void> delete(@PathVariable int id) {
        moduleService.delete(id);
        return Result.success();
    }


    @PostMapping("/save")
    public Result<Void> save(@RequestParam("name") String name,
                             @RequestParam(value = "avatarPath", required = false) String avatarPath) {
        moduleService.save(name, avatarPath);
        return Result.success();
    }

    @GetMapping("/export")
    public void export(HttpServletResponse response) {
        File dataZip = moduleService.export();
        if (Objects.isNull(dataZip) || !dataZip.exists()) {
            throw new RuntimeException("文件导出失败，无zip文件");
        }
        try {
            // 配置文件下载
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            // 下载文件能正常显示中文
            String fileName = "landscape-data.zip";
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            InputStream inputStream = new FileInputStream(dataZip);
            ServletOutputStream out = response.getOutputStream();
            IOUtils.copy(inputStream, out);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("文件下载失败");
        }
    }

}
